package com.boarsoft.boar.file.biz;

import com.boarsoft.boar.entity.AppInstFile;
import com.boarsoft.boar.entity.FileVersion;
import com.boarsoft.boar.file.FileVersionBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.common.util.RandomUtil;
import com.boarsoft.common.util.StringUtil;
import com.boarsoft.hibernate.biz.SimpleBizImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class FileVersionBizImpl extends SimpleBizImpl implements FileVersionBiz {

	@Override
	@Transactional(readOnly = true)
	public FileVersion get(String id) {
		return dao.get(FileVersion.class, id);
	}

	@Override
	@Transactional(readOnly = true)
	public FileVersion getByFileName(String appCode, String fileName, String env) {
		//先根据环境找，如果找不到再去查all的。后面再想怎样优化。
		StringBuilder sb = new StringBuilder()//
				.append("select ").append(FileVersion.class.getName())//
				.append(" where vEnv = '")//
				.append(env)//
				.append("' and cFileId = (select cId from file_info where vCode = '")//
				.append(fileName)//
				.append("' and cAppId = (select cId from app_info where vCode = '")//
				.append(appCode)//
				.append("'))");
		FileVersion fileVersion = dao.find(sb.toString(),FileVersion.class);
		if(fileVersion == null){
			log.info("应用{}文件{}在{}环境根据文件名查询sql:{}",appCode,fileName,env,sb.toString());
			sb = new StringBuilder()//
					.append("select ").append(FileVersion.class.getName())//
					.append(" where vEnv = '")//
					.append("all")//
					.append("' where cFileId = (select cId from file_info where vCode = '")//
					.append(fileName)//
					.append("' and cAppId = (select cId from app_info where vCode = '")//
					.append(appCode)//
					.append("'))");
			fileVersion = dao.find(sb.toString(),FileVersion.class);
			if(fileVersion == null){
				log.warn("应用{}下文件{}在环境{}和all均不存在",appCode,fileName,env);
			}
		}
		return fileVersion;
	}
	@Override
	@Transactional(readOnly = true)
	public List<FileVersion> getByGroup(String appCode, String group, String env) {
		StringBuilder sb = new StringBuilder()//
				.append("select ").append(FileVersion.class.getName())//
				.append(" where vEnv = '")//
				.append(env)//
				.append("' and vGroup = '")//
				.append(group)//
				.append("' and cFileId in (select cid from file_info where cAppId = (select cid from app_info where vCode = '")//
				.append(appCode)//
				.append("'))");
		List<FileVersion> fileVersionList = dao.list(sb.toString(), FileVersion.class);
		return fileVersionList;
	}

	@Override
	@Transactional
	public void save(FileVersion o) {
		if (Util.strIsEmpty(o.getId())) {
			dao.save(o);
		} else {
			dao.merge(o);
		}
	}

	@Override
	@Transactional
	public void active(String id) {
		FileVersion o = dao.get(FileVersion.class, id);
		// 将所有文件版本的状态改为inactive
		StringBuilder sb = new StringBuilder()//
				.append("update ").append(FileVersion.class.getName())//
				.append(" set status=").append(FileVersion.STATUS_INACTIVE)//
				.append(" where fileId='").append(o.getFileId())//
				.append("' and env='").append(o.getEnv())//
				.append("' and group='").append(o.getGroup())//
				.append("' and id!='").append(id).append("'");
		dao.executeUpdate(sb.toString());
		o.setStatus(FileVersion.STATUS_ACTIVE);
	}

	@Override
	@Transactional
	public FileVersion copy(String id, String env) {
		FileVersion o = dao.get(FileVersion.class, id);
		FileVersion a = new FileVersion();
		a.setEnv(o.getEnv());
		a.setFileId(o.getFileId());
		a.setVer("copy of ".concat(o.getVer()));
		a.setCreateTime(Util.getStdmfDateTime());
		a.setLastTime(Util.getStdmfDateTime());
		a.setStatus(FileVersion.STATUS_INACTIVE);
		dao.save(a);
		return a;
	}

	@Override
	@Transactional
	public FileVersion add(FileVersion o) {
		FileVersion f = find(o.getFileId(),o.getEnv(),o.getGroup(),o.getVer());
		if(f!=null&&f.getId()!=null){
			f.setLastTime(Util.getStdfDateTime());
			dao.update(f);
			return f;
		}
		dao.save(o);
		return o;
	}

	@Override
	@Transactional
	public void update(FileVersion o) {
		dao.merge(o);
	}

	@Override
	@Transactional(readOnly = true)
	public PagedResult<FileVersion> list(String fileId, String env, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(FileVersion.class.getName());
		sb.append(" where fileId='").append(fileId).append("'");
		if (Util.strIsNotEmpty(env)) {
			sb.append(" and env='").append(env).append("'");
		}
		if (Util.strIsNotEmpty(key)) {
			sb.append("and (version like '%").append(key);
			sb.append("%' or memo like '%").append(key);
			sb.append("%')");
		}
		String ql = sb.toString();
		int total = dao.getTotal("select count(id)".concat(ql));
		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy);
		} else {
			sb.append(" order by lastTime");
		}
		List<FileVersion> lt = dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<FileVersion>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional(readOnly = true)
	public List<FileVersion> list(String fileId, String env) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(FileVersion.class.getName());
		sb.append(" where fileId='").append(fileId).append("'");
		if (Util.strIsNotEmpty(env)) {
			sb.append(" and env='").append(env).append("'");
		}
		return dao.list(sb.toString(), FileVersion.class);
	}

	@Override
	@Transactional(readOnly = true)
	public List<FileVersion> list(String fileId) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(FileVersion.class.getName());
		sb.append(" where fileId='").append(fileId).append("'");
		return dao.list(sb.toString());
	}

	@Override
	@Transactional(readOnly = true)
	public FileVersion find(String fileId, String env, String group) {
		StringBuilder sb = new StringBuilder();
		//启用文件查找顺序：启用文件（dev1cd（例）->all->''）
		//优先找指定环境 没有再找'all' 最后是''
		FileVersion fv = null;
		sb.append("and fileId='").append(fileId).append("' and env='")//
				.append(env).append("' and group='").append(group)//
				.append("' and status=").append(FileVersion.STATUS_ACTIVE);
		fv = dao.find(FileVersion.class, sb.toString());
		if(fv != null){
			return fv;
		}
		sb.setLength(0);
		sb.append("and fileId='").append(fileId).append("' and env='")//
				.append("all").append("' and group='").append(group)//
				.append("' and status=").append(FileVersion.STATUS_ACTIVE);
		fv = dao.find(FileVersion.class, sb.toString());
		if(fv != null){
			return fv;
		}
		sb.setLength(0);
		sb.append("and fileId='").append(fileId).append("' and env='")
				.append("' and group='").append(group)
				.append("' and status=").append(FileVersion.STATUS_ACTIVE);
		fv = dao.find(FileVersion.class, sb.toString());
		return fv;
	}

	@Override
	@Transactional(readOnly = true)
	public FileVersion find(String fileId, String env, String group, String ver) {
		StringBuilder sb = new StringBuilder();
		sb.append("and fileId='").append(fileId).append("' and env='")
				.append(env).append("'").append(" and group='").append(group)
				.append("' and ver='").append(ver).append("'");
		return dao.find(FileVersion.class, sb.toString());
	}

	@Override
	@Transactional(readOnly = true)
	public List<FileVersion> findByEnv(String appId, String env) {
		StringBuilder where=new StringBuilder().append("and env='").append(env).append("'");
		if(StringUtil.isNotBlank(appId)){
			where.append("and appId='").append(appId).append("'");
		}
		return dao.list(FileVersion.class, where.toString());
	}

	@Override
	@Transactional
	public void delete(String id) {
		dao.delete(FileVersion.class, id);
		StringBuilder sb = new StringBuilder();
		sb.setLength(0);
		sb.append("delete from ").append(AppInstFile.class.getName())
				.append(" where fileVersionId='").append(id).append("'");
		dao.executeUpdate(sb.toString());
	}
}